package com.buxiaoxia.system;

import com.buxiaoxia.business.service.CustomUserService;
import com.buxiaoxia.system.config.MyLogoutSuccessHandler;
import com.buxiaoxia.util.MD5Util;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.web.cors.CorsUtils;

@Configuration
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {
	@Autowired
   private MyLogoutSuccessHandler myLogoutSuccessHandler;
	@Autowired
	public void globalUserDetails(final AuthenticationManagerBuilder auth) throws Exception {

		// 使用自定义认证用户信息
		auth.userDetailsService(customUserService()).passwordEncoder(new PasswordEncoder(){
			//自定义MD5加盐验证
			@Override
			public String encode(CharSequence rawPassword) {
				return MD5Util.encode((String)rawPassword);
			}

			@Override
			public boolean matches(CharSequence rawPassword, String encodedPassword) {
				return encodedPassword.equals(MD5Util.encode((String)rawPassword));
			}
		});

	}

	@Override
	@Bean
	public AuthenticationManager authenticationManagerBean() throws Exception {
		return super.authenticationManagerBean();
	}

	@Override
	protected void configure(final HttpSecurity http) throws Exception {
		http.authorizeRequests().antMatchers("/static*//*").permitAll()
			//解决跨域options请求问题
			.requestMatchers(CorsUtils::isPreFlightRequest).permitAll()
			.anyRequest().authenticated()
			.and().formLogin().loginPage("/login").permitAll()
			// 退出登录后的默认路径
			.and().logout().clearAuthentication(true).logoutSuccessHandler(myLogoutSuccessHandler)
            .and().csrf().disable();
	}



	// 注入自定义的用户获取
	@Bean
	UserDetailsService customUserService() {
		return new CustomUserService();
	}



}
